# -*- coding: utf-8 -*-
from xTkinter import * 
import tkFileDialog
import tkMessageBox as msgBox
import sys
import xmlrpclib
from Validation_Contraintes import *
Validateur =  ValidationContrainte()
import time
class Vue_ReglesAffaireDeclencheur(Frame):
    def __init__(self,master,parent,**cnf):
        self.ListeContraintes = []
        self.ListLabels = []
        self.ListeBoutons = []
        self.ListeTable = []
        self.parent = parent
        self.master=master
        Frame.__init__(self,master,cnf)             
        self.pack(side=LEFT,anchor=NW)
        self.configure(width=800,height=600)
        self.ListeUtilisateurs=xCombobox(self)
        self.ListeUtilisateurs.setLocation(135,7)
        self.ListeUtilisateurs.setWidth(15)
        self.ListeUtilisateurs.setListWidth(25)
        self.ListeUtilisateurs.setListHeight(5)
        self.obtenirTables() 
        self.obtenirDeclencheur()
        self.Intervalle=xCombobox(self, width = 20)
        self.Intervalle.setListWidth(25)
        self.Intervalle.setListHeight(7)
        self.Intervalle.setLocation(x=125,y=25+5)
        self.Intervalle.addItem("'A toutes les 10 secondes'")
        self.Intervalle.addItem("'A toutes les minutes'")
        self.Intervalle.addItem("'A toutes les heures'")
        self.Intervalle.addItem("'A tous les jours'")
        self.Intervalle.addItem("'A toutes les semaines'")
        self.Intervalle.addItem("'Lors dun evenement'")
        self.Dict_Invervalle = {"'A toutes les 10 secondes'":10,
                                'A toutes les minutes':60,
                                'A toutes les heures':60*60,
                                'A tous les jours':60*60*24,
                                'A toutes les semaines':60*60*24*7,
                                 "'Lors dun evenement'":0}
        self.Information = None
        self.Action=xCombobox(self, width = 20)
        self.Action.setListWidth(25)
        self.Action.setListHeight(7)
        self.Action.setLocation(x=275,y=25+5)
        self.Action.addItem("'Afficher un rapport'")
        self.Action.addItem("'Avertissement'")
        

        self.Information=xCombobox(self, width = 20)
        self.Information.setListWidth(25)
        self.Information.setListHeight(7)
        self.Information.setLocation(x=425,y=25+5)
        ListeMenu = self.parent.serveur.ObtenirEnregistrement('PERP_RAPPORT', ['NOM'])[1]
        for Menu in ListeMenu:
            self.Information.addItem("'" + Menu['NOM'] + "'")
        
        
        Requete = "select declencheur_id.nextval from dual"
        Reponse = self.parent.serveur.ExecuterRequeteSQLWhere(Requete)
        if(Reponse[0] == 0):
             msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
        else:
            self.ID_Declencheur = Reponse[1][0][0]
        
        Requete = "select contrainte_id.nextval from dual"
        Reponse = self.parent.serveur.ExecuterRequeteSQLWhere(Requete)
        if(Reponse[0] == 0):
             msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
        else:
            self.ID_Contrainte = Reponse[1][0][0]
            
        self.AssociationColonneChamps = {
                                        "TYPE":self.Action,
                                        "INTERVALLE":self.Intervalle,
                                        "RAPPORTNAME":self.Information,
                                        "UTILISATEUR":self.ListeUtilisateurs}
        
        xButton(self,text="Inserer declencheur",width=12, command = self.InsererDeclencheur ).setLocation(0,0)

    def obtenirTables(self):
        Reponse = self.parent.serveur.ObtenirListeTables(self.parent.user,self.parent.profil)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.ListeTable.append(self.ListeChamps[i][0])
                self.CBTables.addItem(self.ListeChamps[i][0])
                self.CBTables.setText(self.ListeChamps[i][0])
                    
    def obtenirTables(self):
         Reponse = self.parent.serveur.ObtenirEnregistrement('PERP_UTILISATEURS', ['IDENTIFIANT'])
         if(Reponse[0]==1):
            ListeChamps = Reponse[1]
            for i in range(len(ListeChamps)):
                self.ListeUtilisateurs.addItem("'" + ListeChamps[i]['IDENTIFIANT'] + "'")
            self.ListeUtilisateurs.addItem("'Tous les utilisateurs'")
    def obtenirDeclencheur(self):
        
        self.ListeDeclencheur = []
        Reponse = self.parent.serveur.ObtenirEnregistrement('DECLENCHEUR', ['TYPE', 'INTERVALLE', 'DERNIEREFOIS', 'CONTRAINTEID', 'RAPPORTNAME', 'AVERTISSEMENT', 'ID', 'UTILISATEUR'])
        
        ## Reponse = self.parent.serveur.ObtenirEnregistrement('CONTRAINTEDECLENCHEUR', ['MESSAGE','TABLEGAUCHE','CHAMPGAUCHE',  'OPERATEUR', 'TABLEDROITE' , 'ID', 'CHAMPDROITE'])
        for Label in self.ListLabels:
            Label.destroy()
        for Bouton in self.ListeBoutons:
            Bouton.destroy()
        if(Reponse[0]==1):
            self.ListeDeclencheur  = Reponse[1]
            Position = 1
            #self.ListeBoutons.append(xButton(self,text="Ajouter Declencheur",width=16, command = self.AjouterContrainte )
            for Declencheur in self.ListeDeclencheur:
                texte = Declencheur['INTERVALLE'] 
                texte = texte + '  FAIRE  ' + Declencheur['TYPE']
                texte = texte + Declencheur['CONTRAINTEID']
                texte = texte + Declencheur['RAPPORTNAME'] 
                texte = texte + Declencheur['AVERTISSEMENT']
                texte = texte + Declencheur['UTILISATEUR']
                self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
                self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)
                self.ListeBoutons.append(xButton(self,text="Supprimer",width=12, command = lambda declencheur = Declencheur : self.SupprimerDeclencheur(declencheur)))
                self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(600,(Position+1)*25+5)
                Position = Position + 1
#            Position = 1
#            Reponse = self.parent.serveur.ObtenirEnregistrement('CONTRAINTEDECLENCHEUR', ['MESSAGE','TABLEGAUCHE','CHAMPGAUCHE',  'OPERATEUR', 'TABLEDROITE' , 'ID', 'CHAMPDROITE'])
#            Co
#
#            try:
#                texte = Contrainte['MESSAGE'] 
#                texte = texte + '(' + Contrainte['TABLEGAUCHE'] + '.'
#                texte = texte + Contrainte['CHAMPGAUCHE']
#                texte = texte + Contrainte['OPERATEUR']
#                texte = texte + Contrainte['TABLEDROITE']  + '.'
#                texte = texte + Contrainte['CHAMPDROITE']+ ')'
#                self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
#                self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)
#            except:
#                texte = "Contrainte invalide, corrigez-la"
#                self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
#                self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)
#
#            self.ListeBoutons.append(xButton(self,text="Editer",width=12, command = lambda contrainte=Contrainte : self.OuvrirFenetreEdition(contrainte)))
#            self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(500,(Position+1)*25+5)
#            self.ListeBoutons.append(xButton(self,text="Supprimer",width=12, command = lambda contrainte=Contrainte : self.SupprimerContrainte(contrainte)))
#            self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(600,(Position+1)*25+5)
            
                             
        else:
          msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
       
   
        
    def OuvrirFenetreEdition(self, Contrainte):
        root=Toplevel()
        root.geometry('550x175')
        root.grab_set()
        print Contrainte
        vi=Vue_EditionReglesAffaires(Contrainte, root,self)
        root.mainloop()
    
    def InsererDeclencheur(self):
        self.ID_Declencheur =self.ID_Declencheur + 1
        Requete = "insert into DECLENCHEUR ("
        for champs in self.AssociationColonneChamps.keys():
            Requete = Requete + champs + ", "
        Requete =  Requete + " ID) values ("
        for champs in self.AssociationColonneChamps.keys():
            if self.AssociationColonneChamps[champs] <> None:
               Requete = Requete +  self.AssociationColonneChamps[champs].getText() + ", "
            else:
               Requete = Requete +  "''" + ", " 
        Requete =  Requete + str(self.ID_Declencheur) +" )"
        print Requete
        self.parent.serveur.ExecuterRequeteSQL(Requete)
        self.parent.serveur.ExecuterRequeteSQL("commit")
        self.parent.serveur.ExecuterRequeteSQL("update DECLENCHEUR set DERNIEREFOIS = " + (str(time.time()).split(".")[0]) +" where ID = " + str(self.ID_Declencheur))
        self.parent.serveur.ExecuterRequeteSQL("commit")
        self.obtenirDeclencheur()
        
        
    def MettreAJourContrainte(self, Contrainte):
        if Contrainte['ID'] <> '':
            print "Mise a jour" ,Contrainte
            #where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID']}
            where = " where ID = " + str(Contrainte['ID'])
            self.parent.serveur.MettreAJour('CONTRAINTEDECLENCHEUR', Contrainte, where)
            
            
        else:
            Contrainte['ID'] = str(self.ID_Declencheur)
            print "ajouter" ,Contrainte
            print self.ID_Declencheur
            self.ID_Declencheur = self.ID_Declencheur + 1
            self.parent.serveur.InsererEnregistrement('CONTRAINTEDECLENCHEUR', Contrainte)
        self.obtenirContraintes()
    
#    def SupprimerContrainte(self, Contrainte):
#       
#        Contrainte['ID'] = "null"
#        print "a effacer " , Contrainte
#        where = " where ID = " + str(Contrainte['ID'])
#        self.parent.serveur.EffacerEnregistrement('CONTRAINTEDECLENCHEUR', where)
        
    def SupprimerDeclencheur(self, Declencheur):
        if Declencheur['ID'] == '':
            where = " where ID is null " 
        else:
            where = " where ID = " + str(Declencheur['ID'])
        self.parent.serveur.EffacerEnregistrement('DECLENCHEUR', where)
        self.obtenirDeclencheur()  

    def AjouterContrainte(self):
        root=Toplevel()
        root.geometry('600x175')
        vi=Vue_EditionReglesAffaires(None, root,self)
        root.mainloop()
    
    def PlacerContrainte(self):
        pass
    
#    def Regle(self):
#        for x in range (1600/25):
#            X = x*25
#            xLabel(self, text=str(X)).setLocation(X,0)
#        for y in range (1200/25):
#            Y = y*25
#            xLabel(self, text=str(Y)).setLocation(0,Y)      

        

class Vue_EditionReglesAffaires(Frame):
    def __init__(self,Contrainte, master,parent,**cnf):
        KeysList=cnf.keys()
        self.parent = parent
        self.master=master
        self.width=550
        self.height=175
        if ('width' in KeysList):
            self.width=cnf['width']
        if ('height' in KeysList):
            self.height=cnf['height']
        Frame.__init__(self,master,cnf)        
        self.config(bg='Floralwhite')#(bg='#6B979C',relief='raised',bd=3)
        self.pack(side=LEFT, anchor=NW)
        self.configure(width=550,height=175)
        self.Contrainte = Contrainte
       # self.Regle()
    
                       
        Ligne1 = 30
        Ligne2 = 55
        xButton(self,text="Fermer",width=12, command = self.Quitter ).setLocation(400,125)
        
#        self.BoutonDynamiqueStatique = xButton(self,text="Statique",width=12, command = self.DynamiqueStatique )
#        self.BoutonDynamiqueStatique.setLocation(400,5)
       
        
        self.Table_Gauche=xCombobox(self,width=20)
        self.Table_Gauche.setLocation(x=0,y=0)
        
        self.Table_Gauche.setListWidth(25)
        self.Table_Gauche.setListHeight(5)
        
        self.Champ_Gauche=xCombobox(self,width=20)
        self.Champ_Gauche.setLocation(x=5,y=Ligne2)
        
        self.Champ_Gauche.setListWidth(25)
        self.Champ_Gauche.setListHeight(5)
        
    
        self.Comparaison=xCombobox(self)
        self.Comparaison.width=10
        self.Comparaison.setListWidth(25)
        self.Comparaison.setListHeight(5)
        self.Comparaison.setLocation(x=150,y=Ligne2)
        
        self.Table_Droite=xCombobox(self,width=20)
        self.Table_Droite.setLocation(x=400,y=Ligne2)  
        
        self.Champ_Droite=xCombobox(self,width=20)
        self.Champ_Droite.setLocation(x=400,y=Ligne2) 
        self.Champ_Droite.setListWidth(20)
        self.Champ_Droite.setListHeight(5)
        
        self.Table_Droite=xCombobox(self,width=20)
        self.Table_Droite.setLocation(x=250,y=Ligne2)
        
        self.Table_Droite.setListWidth(25)
        self.Table_Droite.setListHeight(5)
        
        self.Message=xEntry(self,text='Message d''erreur',width=60)
        self.Message.setLocation(x=5,y=100)

            
        
        self.AssociationColonneChamps = {
                                        "TABLEGAUCHE":self.Table_Gauche,
                                        "CHAMPGAUCHE":self.Champ_Gauche,
                                        "OPERATEUR":self.Comparaison,
                                        "TABLEDROITE":self.Table_Droite,
                                        "CHAMPDROITE":self.Champ_Droite,
                                        "MESSAGE":self.Message
                                        }
        self.initialiserComboBox()
        self.Table_Droite.setValidator(self.ObtenirChampsDroite)
        self.Table_Gauche.setValidator(self.ObtenirChampsGauche)
        self.RemplirChamp(self.Contrainte)
        
        pass

#    def DynamiqueStatique(self):
#        if self.BoutonDynamiqueStatique.getText() == "Dynamique":
#            self.BoutonDynamiqueStatique.setText("Statique")
#            self.Attribut_Operande_Droite.setVisible(False) 
#            self.Attribut2_Label.setVisible(False) 
#        else:
#            self.BoutonDynamiqueStatique.setText("Dynamique")
#            self.Attribut_Operande_Droite.setVisible(True) 
#            self.Attribut2_Label.setVisible(True)
    def obtenirTables(self):
        Reponse = self.parent.parent.serveur.ObtenirListeTables(self.parent.parent.user,self.parent.parent.profil)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.Table_Gauche.addItem(self.ListeChamps[i][0])
                self.Table_Droite.addItem(self.ListeChamps[i][0])
        self.Table_Gauche.setText("<chosir>")
        self.Table_Droite.setText("<chosir>")   
            
    def Quitter(self):
        #if MsgBox.askokcancel("Attention", "Vous annulez l'ouverture de session."):
        self.destroy()
        self.master.destroy()
        if self.Contrainte == None:
            self.Contrainte={}
            self.Contrainte['ID'] = ''
        for champs in self.AssociationColonneChamps.keys():
            if self.AssociationColonneChamps[champs] <> None:
                self.Contrainte[champs] = self.AssociationColonneChamps[champs].getText()
        self.parent.MettreAJourContrainte(self.Contrainte)
        pass
    
    def close(self):
        self.destroy()
        pass
    
    def ObtenirChampsDroite(self):
        self.Champ_Droite.clear()
        self.Champ_Droite.setListHeight(5)
        if self.Table_Droite.getText() <> "<<STATIQUE>>":
            for Champ in self.parent.parent.serveur.ObtenirListeChamps(self.Table_Droite.getText())[1]:
                    self.Champ_Droite.addItem(Champ[0])
        else:
            self.Champ_Droite.setText('')
     
    def ObtenirChampsGauche(self):
        self.Champ_Gauche.clear()
        self.Champ_Gauche.setListHeight(5)
        if self.Table_Gauche.getText() <> "<<STATIQUE>>":
            for Champ in self.parent.parent.serveur.ObtenirListeChamps(self.Table_Gauche.getText())[1]:
                    print Champ
                    self.Champ_Gauche.addItem(Champ[0])
        else:
            self.Champ_Gauche.setText('')
                            
    def initialiserComboBox(self):
        #operande
        for Operande in Validateur.getOperande():
            self.Comparaison.addItem(Operande)
        print  self.parent.ListeTable
        self.Table_Droite.addItem("<<STATIQUE>>")
        self.obtenirTables()
    
    def RemplirChamp(self, Contrainte):
        print Contrainte
        if self.Contrainte == None:
            for Champs in self.AssociationColonneChamps.keys():
                try:
                    if self.AssociationColonneChamps[Champs] <> None:
                        self.AssociationColonneChamps[Champs].setText('')
                    
                except:
                    pass
        else:
            for Champs in self.Contrainte:
                try:
                    if self.AssociationColonneChamps.has_key(Champs):
                        if self.AssociationColonneChamps[Champs] <> None:
                            self.AssociationColonneChamps[Champs].setText(Contrainte[Champs])
                except:
                    pass
        pass   

    def Regle(self):
        for x in range (1600/25):
            X = x*25
            xLabel(self, text=str(X)).setLocation(X,0)
        for y in range (1200/25):
            Y = y*25
            xLabel(self, text=str(Y)).setLocation(0,Y)       
#
#
#class Controleur:
#    def __init__(self):
#        self.user = "ADMIN"
#        self.profil = "ADMIN"
#        Serveur='http://localhost:8000'
#        self.serveur=xmlrpclib.ServerProxy(Serveur)
#        root=Tk()
#        root.geometry('800x400')
#        vi=Vue_ReglesAffaireDeclencheur(root,self)
#        root.mainloop()       
#
#Controleur = Controleur()

    
    
    
